package com.crayon2f.test.pdf;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PdfToImage {
    public static void exportPageAsImage(String pdfPath, int pageIndex, String outputImagePath) throws IOException {
        try (PDDocument document = Loader.loadPDF(new File(pdfPath))) {
            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage image = renderer.renderImageWithDPI(pageIndex, 300); // DPI可调
            ImageIOUtil.writeImage(image, outputImagePath, 300); // 自动根据扩展名选择格式
        }
    }

    public static void main(String[] args) {
        try {
            exportPageAsImage("input.pdf", 0, "output.png"); // 导出第1页（索引0）
            System.out.println("导出成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}